package com.carlton.demo.util;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

public class JsonUtil {

	/**
	 * 将一个json字符串转换成一个Object对象
	 * 
	 * @param jsonString
	 * @return
	 */
	public static Object getObjectFromJsonString(String jsonString) {
		JSONObject o = JSONObject.fromObject(jsonString);
		return JSONObject.toBean(o);
	}

	public static JSONArray getJSONArrayFormString(String str) {
		if (str == null || str.trim().length() == 0) {
			return null;
		}
		JSONArray jsonArray = null;
		try {
			jsonArray = JSONArray.fromObject(str);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return jsonArray;
	}

	public static JSONObject StringToJSONOBject(String str) {
		if (str == null || str.trim().length() == 0) {
			return null;
		}
		JSONObject jsonObject = null;
		try {
			jsonObject = JSONObject.fromObject(str);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return jsonObject;
	}

	public static String OjbectToString(Object obj) {
		JSONObject json = JSONObject.fromObject(obj);
		return json.toString();
	}

	public static Object stringToObject(String str, @SuppressWarnings("rawtypes") Class clazz) {
		if (str == null || str.trim().length() == 0) {
			return null;
		}
		Object obj = null;
		JSONObject jsonObject = null;
		try {
			jsonObject = JSONObject.fromObject(str);
			obj = JSONObject.toBean(jsonObject, clazz);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return obj;
	}
}
